package edu.xmut.yuepai.sys.controller;

import edu.xmut.yuepai.model.entity.SysPicture;
import edu.xmut.yuepai.sys.service.SysPictureService;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RequestMapping("/sys-picture")
@RestController
public class SysPictureController {

    @Resource
    private SysPictureService sysPictureService;

    @PostMapping("/save")
    public Boolean savePicture(@RequestBody SysPicture sysPicture) {
        return sysPictureService.save(sysPicture);
    }

    @PostMapping("/save-batch/blog")
    public Long saveBatchBlogPicture(@RequestParam("blogId") Long blogId, @RequestBody List<String> imageIds) {
        long index = 0;
        try {
            for (String imageId : imageIds) {
                sysPictureService.lambdaUpdate()
                        .set(SysPicture::getBlogId, blogId)
                        .set(SysPicture::getSort, index)
                        .eq(SysPicture::getId, imageId)
                        .update();
                index++;
            }
        } catch (Exception e) {
            return 0L;
        }
        return index;
    }

    @GetMapping("/blog/{blogId}")
    public List<SysPicture> getBlogPictureByBlogId(@PathVariable("blogId") Long blogId) {
        return sysPictureService.lambdaQuery()
                .eq(SysPicture::getBlogId, blogId)
                .orderBy(true, true, SysPicture::getSort)
                .list();
    }

    @GetMapping("/blog/cover/{id}")
    public SysPicture getBlogCover(@PathVariable("id") String id) {
        return sysPictureService.lambdaQuery().eq(SysPicture::getId, id).one();
    }

    @PostMapping("/save-batch/yuepai")
    public Long saveBatchYuePaiPicture(@RequestParam("yuepaiId") Long yuepaiId, @RequestBody List<String> imageIds) {
        long index = 0;
        for (String imageId : imageIds) {
            sysPictureService.lambdaUpdate()
                    .set(SysPicture::getYuepaiId, yuepaiId)
                    .set(SysPicture::getSort, index)
                    .eq(SysPicture::getId, imageId)
                    .update();
            index++;
        }
        return index;
    }

}
